from socket import socket, AF_INET, SOCK_STREAM


class TCP:
    def __init__(self):
        from constants import config
        self.host = config.get("web", "tcp_host")
        self.port = int(config.get("web", "tcp_port"))
        self.buf_size = int(config.get("web", "tcp_buf_size"))
        self.address = (self.host, self.port)
        self.client = socket(AF_INET, SOCK_STREAM)
        self.is_run = True
        self.local_address = None

    def Run(self):
        self.client.connect(self.address)
        self.local_address = self.client.getsockname()
        from Lib.Utils import Console
        Console(f"开启 TCP 服务: {self.host}: {self.port}")
        print(self.Send("111111111"))

        while self.is_run:
            data = self.client.recv(self.buf_size)
            print(data)

    def Close(self):
        self.is_run = False

    def GetQrLoginImage(self):
        token_dict = {'address': self.local_address}
        from constants import config
        import jwt
        jwt_token = jwt.encode(token_dict, config.get('web', "tcp_jwt_key"))
        from Lib.Utils import Console
        from constants import http_client
        url = http_client.GeneratorUrl(f"user/oauth/{jwt_token}")
        Console(f"二维码地址:", "info")
        Console(f"{url}", "info")
        from Lib import Utils
        Utils.GeneratorQRCode(url, f"{config.get('base', 'resource_path')}qr.png")

    def Send(self, message):
        ...
